@tool
class_name AttributeSet
extends Resource

#region 属性
@export var attributes:Array[Attribute]
## 运行时数据
var attributes_runtime_dict:Dictionary[String,Attribute] = {}
var init_args:Dictionary = {}
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region Setter
func setter_attributes(value):
	attributes = value

	_create_runtime_attributes()
	_init_attributes()
#endregion
#region 基类方法
#endregion
#region 公共方法
func init(args:Dictionary = {}):
	init_args = args
	
	_create_runtime_attributes()
	_init_attributes()
func find_attribute(attribute_name:String) -> Attribute:
	if attributes_runtime_dict.get(attribute_name):
		return attributes_runtime_dict.get(attribute_name)
	else:
		push_error("AttributeSet 未能找到指定属性：{0}".format([attribute_name]))
		return null
func add_attribute(attribute_name:String,property_type:CompositeProperty.PropertyType,init_value) -> Attribute:
	if not attributes.any(func(attr:Attribute):return attr.attribute_name == attribute_name):
		var attribute = Attribute.new()
		attribute.resource_local_to_scene = true
		var base_value = CompositeProperty.new()
		base_value.resource_local_to_scene = true
		base_value.init(property_type,init_value)
		attribute.attribute_name = attribute_name
		attribute.init(self,{BaseValue = base_value})
		if Engine.is_editor_hint():
			attributes.append(attribute)
		else:
			attributes_runtime_dict.set(attribute_name,attribute)
		return attribute
	return null
#endregion
#region 私有方法
func _create_runtime_attributes():
	for attribute:Attribute in attributes_runtime_dict.values():
		attribute.destroy()
	attributes_runtime_dict.clear()
	for attribute in attributes:
		if attributes_runtime_dict.has(attribute.attribute_name):
			push_warning("AttributeSet 有重复的属性名：{0}".format([attribute.attribute_name]))
			continue
		var attribute_duplicated = attribute.duplicate(true) as Attribute
		attribute_duplicated.init(self)
		attributes_runtime_dict.set(attribute_duplicated.attribute_name,attribute_duplicated)
func _init_attributes():
	for attribute_name in attributes_runtime_dict.keys():
		var runtime_attribute = attributes_runtime_dict.get(attribute_name)
		runtime_attribute.recompute_attribute()
#endregion
#region 生命周期函数
func _init() -> void:
	if Engine.is_editor_hint():
		resource_local_to_scene = true
#endregion
